package com.dg.service.impl;

import com.dg.dao.DeptMapper;
import com.dg.dao.UserMapper;
import com.dg.exception.ParamException;
import com.dg.param.DeptParam;
import com.dg.pojo.Dept;
import com.dg.service.DeptService;
import com.dg.util.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Dept> list(){
        List<Dept> list = deptMapper.getAll();
        Collections.sort(list, deptSeqComparator);
        return list;
    }

    @Override
    public void save(DeptParam param) {
        ValidatorUtil.validate(param);
        if(checkExist(param.getId(), param.getName())){
            throw new ParamException("部门名称已存在");
        }
        Dept dept = Dept.builder().name(param.getName()).seq(param.getSeq()).remark(param.getRemark())
                .operator("admin").operateIp("127.0.0.1").operateTime(new Date()).build();
        deptMapper.insertSelective(dept);
    }

    @Override
    public void update(DeptParam param){
        ValidatorUtil.validate(param);
        if(!checkExist(param.getId(), param.getName())){
            throw new ParamException("部门名称已存在");
        }
        Dept dept = Dept.builder().id(param.getId()).name(param.getName()).seq(param.getSeq()).remark(param.getRemark())
                .operator("admin").operateIp("127.0.0.1").operateTime(new Date()).build();
        deptMapper.updateByPrimaryKeySelective(dept);
    }

    @Override
    public void delete(Integer id) {
        if(id == null) {
            throw new ParamException("id不能为空");
        }
        if(!checkUserExistByDeptId(id)){
            throw new ParamException("部门列表下面有用户，无法删除");
        }

        deptMapper.deleteByPrimaryKey(id);
    }

    private boolean checkExist(Integer id, String name) {
        return deptMapper.findByName(id,name) > 0;
    }

    private boolean checkUserExistByDeptId(Integer id) {
        return userMapper.countByDeptId(id) > 0;
    }

    private Comparator<Dept> deptSeqComparator = new Comparator<Dept>() {
        @Override
        public int compare(Dept o1, Dept o2) {
            return o1.getSeq() - o2.getSeq();
        }
    };

}
